package com.itwenke.springbootdemo.shirowebboot.session;

import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SessionKey;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.WebSessionKey;

import javax.servlet.ServletRequest;
import java.io.Serializable;

public class DefaultRedisWebSessionManager extends DefaultWebSessionManager {

    @Override
    protected Session retrieveSession(SessionKey sessionKey) throws UnknownSessionException {
        Serializable sessionId = getSessionId(sessionKey);

        if(sessionKey instanceof WebSessionKey){
            WebSessionKey webSessionKey = (WebSessionKey) sessionKey;
            ServletRequest request = webSessionKey.getServletRequest();
            Session session = (Session) request.getAttribute(sessionId + "");
            if(session != null){
                return session;
            }else{
                session = retrieveSessionFromDataSource(sessionId);
                if (session == null) {
                    String msg = "Could not find session with ID [" + sessionId + "]";
                    throw new UnknownSessionException(msg);
                }
                request.setAttribute(sessionId + "", session);
                return session;
            }
        }
        return null;
    }
}
